import request from './index';

// WebSocket 连接
let ws = null;
let messageCallback = null;
let reconnectAttempts = 0;
const MAX_RECONNECT_ATTEMPTS = 3;
const RECONNECT_INTERVAL = 3000;

// 初始化 WebSocket 连接
export const initWebSocket = (callback) => {
    messageCallback = callback;
    const token = localStorage.getItem('token');
    if (!token) {
        console.error('No token found');
        return;
    }

    // 创建 WebSocket 连接
    ws = new WebSocket(`ws://localhost:8066/customer?token=${token}`);

    ws.onopen = () => {
        console.log('WebSocket connected');
        reconnectAttempts = 0; // 重置重连次数
    };

    ws.onmessage = (event) => {
        try {
            const message = JSON.parse(event.data);
            if (messageCallback) {
                messageCallback(message);
            }
        } catch (error) {
            console.error('Error parsing message:', error);
        }
    };

    ws.onerror = (error) => {
        console.error('WebSocket error:', error);
    };

    ws.onclose = () => {
        console.log('WebSocket disconnected');
        // 尝试重连
        if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
            setTimeout(() => {
                reconnectAttempts++;
                initWebSocket(callback);
            }, RECONNECT_INTERVAL);
        }
    };
};

// 发送消息
export const sendMessage = (message) => {
    if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify(message));
        return true;
    } else {
        console.error('WebSocket is not connected');
        return false;
    }
};

// 关闭 WebSocket 连接
export const closeWebSocket = () => {
    if (ws) {
        ws.close();
        ws = null;
        messageCallback = null;
    }
};

// 获取连接状态
export const getConnectionState = () => {
    if (!ws) return 'CLOSED';
    switch (ws.readyState) {
        case WebSocket.CONNECTING:
            return 'CONNECTING';  // 连接中
        case WebSocket.OPEN:
            return 'OPEN';        // 已连接
        case WebSocket.CLOSING:
            return 'CLOSING';     // 关闭中
        case WebSocket.CLOSED:
            return 'CLOSED';      // 已关闭
        default:
            return 'UNKNOWN';     // 未知状态
    }
};

// 获取历史消息
export const getHistoryMessages = (sender, receiver) => {
    if (!sender || !receiver) {
        console.error('sender和receiver参数不能为空')
        return Promise.reject(new Error('参数错误'))
    }
    return request({
        url: '/chat/history',
        method: 'get',
        params: {
            sender,
            receiver
        },
        timeout: 10000 // 增加超时时间到10秒
    })
};

// 获取客服列表
export const getCustomerServiceList = () => {
    return request({
        url: '/customer/list',
        method: 'get'
    });
}; 